#!/bin/sh
#
# tproxy -- start the transparent proxy client
#
# Copyright (C) 2016-2020 Wu Zhangjin <lzufalcon@163.com>
#
# Note: scripts/proxy-client-transparent.sh of https://github.com/tinyclub/cloud-ubuntu
#

uname | grep -q MINGW && PWD_OPT="-W"
TOP_DIR="$(cd "$(dirname "$0")"/../../ && pwd $PWD_OPT)"
. "$TOP_DIR"/tools/docker/config $* >/dev/null

IMAGE_NAME=tinylab/$TPROXY_IMAGE_NAME

[ -z "$PULL" ] && PULL=0

docker images | grep -q $IMAGE_NAME
[ $? -ne 0 -o $PULL -eq 1 ] && docker pull $IMAGE_NAME

[ -z "$PROXY_PORT" ] && PROXY_PORT=1080
EXTRA_ARGS="$EXTRA_ARGS -e PROXY_PORT=$PROXY_PORT"

[ -n "$MAP_PORT" -a "x$MAP_PORT" = "x1" ] && EXTRA_ARGS="$EXTRA_ARGS -p $PROXY_PORT:$PROXY_PORT"

[ -n "$PROXY_LIMIT" ] && EXTRA_ARGS="$EXTRA_ARGS -e PROXY_LIMIT=$PROXY_LIMIT"
[ -n "$PROXY_DOWN_LIMIT" ] && EXTRA_ARGS="$EXTRA_ARGS -e PROXY_DOWN_LIMIT=$PROXY_DOWN_LIMIT"
[ -n "$PROXY_UP_LIMIT" ] && EXTRA_ARGS="$EXTRA_ARGS -e PROXY_UP_LIMIT=$PROXY_UP_LIMIT"
[ -n "$PROXY_SPEED" ] && EXTRA_ARGS="$EXTRA_ARGS -e PROXY_SPEED=$PROXY_SPEED"
[ -n "$PROXY_DOWN_SPEED" ] && EXTRA_ARGS="$EXTRA_ARGS -e PROXY_DOWN_SPEED=$PROXY_DOWN_SPEED"
[ -n "$PROXY_UP_SPEED" ] && EXTRA_ARGS="$EXTRA_ARGS -e PROXY_UP_SPEED=$PROXY_UP_SPEED"

# Available encrypt cmds: sha1sum, sha224sum, cksum, sha256sum, sha512sum, md5sum, sha384sum, sum
[ -z "$ENCRYPT_CMD" ] && ENCRYPT_CMD="cat"
[ -n "$PROXY_PWD" ] && PROXY_PWD=`echo $PROXY_PWD | tr -d '\n' | $ENCRYPT_CMD | cut -d' ' -f1 | cut -c1-30`

[ -z "$HOST_NAME" ] && HOST_NAME=localhost
[ -z "$UNIX_PWD" ] && UNIX_PWD=ubuntu
[ -z "$VNC_PWD" ] && VNC_PWD=ubuntu
[ -z "$PORT_MAP" ] && PORT_MAP="$DEFAULT_PORT_MAP"
[ -z "$ENV_ARGS" ] && ENV_ARGS=" -e UNIX_PWD=$UNIX_PWD -e VNC_PWD=$VNC_PWD -e SCREEN_SIZE=$SCREEN_SIZE -e PROXY_SERVER=$PROXY_SERVER -e PROXY_PWD=$PROXY_PWD"
[ -z "$EXTRA_ARGS" ] && EXTRA_ARGS=""

[ -n "$TPROXY_IP" ] && ip="--ip=$TPROXY_IP"
TPROXY_NET="$ip --network $VNC_NET_NAME"

docker run --dns 127.0.0.1 $TPROXY_NET \
	--name $TPROXY_NAME --privileged -d -t \
	$PORT_MAP $ENV_ARGS $TPROXY_LIMITS $EXTRA_ARGS \
	-h $HOST_NAME $IMAGE_NAME
